package security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 定义用户信息服务
     * @return
     */
//    @Bean
//    public UserDetailsService getUserDetailService(){
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withUsername("zhangsan").password("1234").authorities("p1").build());
//        manager.createUser(User.withUsername("lisi").password("1234").authorities("p2").build());
//        return manager;
//    }
    /**
     * 定义密码编辑器，加密策略
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }
    /**
     * 定义安全拦截机制
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/r/r1").hasAuthority("p1") // /r/r1需要有p1权限才能访问
                .antMatchers("/r/r2").hasAuthority("p2")  // /r/r2 需要p2权限访问
                .antMatchers("/r/**").authenticated()
                .anyRequest().permitAll()  //除了 /r/** 其它请求都能访问
        .and()
                .formLogin()
                .successForwardUrl("/login-success");
    }
}
